package com.study.security;

import com.study.utils.utils.R;
import com.study.utils.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 1.LogoutHandler是SpringSecurity中提供的退出的接口
 * 步骤：1.移除token
 *      2.针对redis的操作删除token
 */
public class TokenLogoutHandler implements LogoutHandler {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
  public TokenLogoutHandler(TokenManager tokenManager,RedisTemplate redisTemplate){
      this.tokenManager=tokenManager;
      this.redisTemplate=redisTemplate;
    }
    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        //1.从header中获取token
        String token = httpServletRequest.getHeader("token");
        //2.token不为空，移除token 从redis删除token
        if (token!=null){
            tokenManager.removeToken(token);
            String username = tokenManager.getUserInfoFromToken(token);
            redisTemplate.delete(username);
        }
        ResponseUtil.out(httpServletResponse,R.ok());
    }
}
